package com.my.algorithmlearning.leetcode;

import com.my.algorithmlearning.entity.TreeNode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @ClassName InorderTraversal
 * @Description InorderTraversal
 * @Author wanghaiwei
 * @Date 2022/11/23 9:47
 */
public class InorderTraversal {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        result.addAll(inorderTraversal(root.left));
        result.add(root.val);
        result.addAll(inorderTraversal(root.right));
        return result;
    }

    public List<Integer> inorderTraversalByIterator(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> traversalStack = new ArrayDeque<>();
        while(true) {
            if(root != null) {
                traversalStack.push(root);
                root = root.left;
            }else if(!traversalStack.isEmpty()){
                root = traversalStack.pop();
                result.add(root.val);
                root = root.right;
            }else {
                break;
            }
        }
        return result;
    }

    public boolean equalAssert(String expectedStr, List<Integer> result) {
        return expectedStr.equals(StringUtils.join(result, ','));
    }

    public static void main(String[] args) {
        InorderTraversal solution = new InorderTraversal();
        TreeNode root = new TreeNode(1);
        Assert.isTrue(solution.equalAssert("1", solution.inorderTraversal(root)), "递归实现-[1]结果错误");
        Assert.isTrue(solution.equalAssert("1", solution.inorderTraversalByIterator(root)), "迭代实现-[1]结果错误");
        root.left = null;
        TreeNode right = new TreeNode(2);
        right.left = new TreeNode(3);
        root.right = right;
        Assert.isTrue(solution.equalAssert("1,3,2", solution.inorderTraversal(root)), "递归实现-[1,null,2,3]结果错误");
        Assert.isTrue(solution.equalAssert("1,3,2", solution.inorderTraversalByIterator(root)), "迭代实现-[1,null,2,3]结果错误");
    }
}
